<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="99px" style="padding-right: 5px;">
      <el-row>
        <el-col :span="8">
          <el-form-item label="发起党组织:" prop="deptId" style="width: 100%;">
            <el-tree-select
              v-model="queryParams.deptId"
              :data="deptOptions"
              :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
              value-key="deptId"
              placeholder="请选择发起党组织"
              check-strictly
              style="width: 414px"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="活动时间" prop="startTime" style="width: 100%;">
            <el-date-picker
                v-model="dateRange"
                value-format="YYYY-MM-DD"
                type="daterange"
                range-separator="-"
                start-placeholder="时间起"
                end-placeholder="时间止"
                style="width: 430px"
            ></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="状态" prop="status" style="width: 100%;">
            <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
              <el-option
                v-for="dict in sys_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"/>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <el-row :gutter="10" class="mb8" style="margin: 15px 0px;">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['partybuilding:Review:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" @handleQuery="handleQuery" @resetQuery="resetQuery"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="reviewList" @selection-change="handleSelectionChange">
      <el-table-column label="主题" align="left" prop="title" width="200"/>
      <el-table-column label="所属组织" align="left" prop="deptName" min-width="190"/>
      <el-table-column label="开始时间" align="left" prop="begin" width="200">
        <template #default="scope">
          <span>{{ scope.row.begin!=null? parseTime(scope.row.begin, '{y}-{m}-{d}') : '' }} </span>
        </template>
      </el-table-column>
      <el-table-column label="结束时间" align="left" prop="end" width="200">
        <template #default="scope">
          <span>{{ scope.row.end!=null? parseTime(scope.row.end, '{y}-{m}-{d}') : '' }}</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="left" prop="status" width="200">
        <template #default="scope">
            <dict-tag :options="sys_status" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="left" class-name="small-padding fixed-width" min-width="190">
        <template #default="scope">
          <el-button link type="danger" @click="openPeopleReview(scope.row)" v-hasPermi="['partybuilding:Review:queryMy']" v-if="scope.row.status===0">互评情况</el-button>
          <el-divider direction="vertical" v-hasPermi="['partybuilding:Review:queryMy']" v-if="scope.row.status===0"/>
          <el-button link type="danger" @click="openOrgReview(scope.row)" v-hasPermi="['partybuilding:Review:orgReview']">支部评定</el-button>
          <el-divider direction="vertical" v-hasPermi="['partybuilding:Review:orgReview']"/>
          <el-button link type="danger" @click="openReviewResult(scope.row)" v-hasPermi="['partybuilding:Review:result']">评定结果</el-button>
          <el-divider direction="vertical" v-hasPermi="['partybuilding:Review:result']"/>
          <el-button link type="danger" @click="handleView(scope.row)">查看</el-button>
          <el-divider direction="vertical" v-if="scope.row.status===2"/>
          <el-button link type="danger" @click="handleDelete(scope.row)" v-hasPermi="['partybuilding:Review:remove']" v-if="scope.row.status===2">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改评议对话框 -->
    <el-dialog :title="title" v-model="open" width="900px" append-to-body>
      <el-form ref="ReviewRef" :model="form" :rules="rules" label-width="109px">
        <el-row>
          <el-col :span="24">
            <el-form-item label="发起组织" prop="deptId">
              <el-tree-select
                  v-model="form.deptId"
                  :data="deptOptions"
                  :props="{ value: 'deptId', label: 'deptName', children: 'children' }"
                  value-key="deptId"
                  placeholder="请选择所属组织"
                  check-strictly
                  @node-click="handleClickOrginize"
                  :disabled="isDisabled"
              />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="民主评议主题" prop="title">
              <el-input v-model="form.title" placeholder="请输入民主评议主题" :disabled="isDisabled" clearable></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="开始时间" prop="begin">
              <el-date-picker clearable
                v-model="form.begin"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择开始时间"
                style="width: 100%;"
                :disabled-date="disabledDateBegin"
                :disabled="isDisabled">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束时间" prop="end">
              <el-date-picker clearable
                v-model="form.end"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="请选择结束时间"
                style="width: 100%;"
                :disabled-date="disabledDateEnd"
                :disabled="isDisabled">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!--<el-col :span="24">
            <div style="margin: 1px 20px 20px 107px;color: red;">活动时间是党员互评的时间，活动结束后请开展支部评定</div>
          </el-col>-->
          <el-col :span="24">
            <el-form-item label="评议说明" prop="details">
              <el-input v-model="form.details" type="textarea" rows="5" placeholder="请输入评议说明" :disabled="isDisabled"/>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item class="formPeopleStyle" label="民主评议对象" prop="bpyPeopleIdList">
              <div class="personDiv">
                <div v-for="(item, index) in bpyPeopleNameList" :key="index" class="singlePersonDiv">
                  <div class="closeDiv" @click="closePerson(index, 'bpy')" v-if="!isDisabled"><el-icon color="#999"><CloseBold /></el-icon></div>
                  <div class="circleAndText">
                      {{ item ? item.substring(1,3) : '' }}
                  </div>
                  <div class="bottomText">
                      {{ item }}
                  </div>
                </div>
                <div class="singlePersonDiv" @click="handleClickBpyPeople" v-if="!isDisabled">
                  <div class="circleAndText" style="background-color:#fff!important;border: 1px solid #ccc;">
                    <el-icon size="25" style="margin-top: 9px;margin-left: 0px;"><Plus /></el-icon>
                  </div>
                  <div class="bottomText">添加人员</div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item class="formPeopleStyle1" label="评议人员" prop="pyPeopleIdList">
              <div class="personDiv">
                <div v-for="(item, index) in pyPeopleNameList" :key="index" class="singlePersonDiv">
                  <div class="closeDiv" @click="closePerson(index, 'py')" v-if="!isDisabled"><el-icon color="#999"><CloseBold /></el-icon></div>
                  <div class="circleAndText">
                      {{ item ? item.substring(0,1) : '' }}
                  </div>
                  <div class="bottomText">
                      {{ item }}
                  </div>
                </div>
                <div class="singlePersonDiv" @click="handleClickPyPeople" v-if="!isDisabled">
                  <div class="circleAndText" style="background-color:#fff!important;border: 1px solid #ccc;">
                    <el-icon size="25" style="margin-top: 9px;margin-left: 0px;"><Plus /></el-icon>
                  </div>
                  <div class="bottomText">添加人员</div>
                </div>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
              <el-form-item label="附件" prop="files">
                <file-upload
                    v-model="form.files"
                    :multiple="true"
                    :isDisabled="isDisabled"
                    :limit="10"
                    :file-type="['doc', 'docx', 'pdf']"
                    :file-size="200">
                </file-upload>
              </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm" v-if="!isDisabled">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 互评弹窗 -->
    <people-review ref="peopleReviewRef" @callBack="getList"/>

    <!-- 支部评定弹窗 -->
    <org-review ref="orgReviewRef" @callBack="getList"/>

    <!-- 评定结果弹窗 -->
    <review-result ref="reviewResultRef" @callBack="getList"/>

    <!-- 评议人员弹窗 -->
    <select-people ref="pyPeopleRef" :parentMethod="pyPeopleMethod"></select-people>
    <!-- 被评议人员弹窗 -->
    <select-people ref="bpyPeopleRef" :parentMethod="bpyPeopleMethod"></select-people>
  </div>
</template>

<script setup name="Review">
import { listReview, getReview, delReview, addReview } from "@/api/partybuilding/Review";
import { listOrg } from "@/api/partybuilding/Org";
import SelectPeople from '../MeetingInfo/component/SelectPeople.vue'
import PeopleReview from './component/PeopleReview.vue'
import OrgReview from './component/OrgReview.vue'
import ReviewResult from './component/ReviewResult.vue'
const { proxy } = getCurrentInstance();
const reviewList = ref([]);
const open = ref(false);
const isDisabled = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const dateRange = ref([]);
const deptOptions = ref(undefined);
const pyPeopleIdList = ref([]);
const pyPeopleNameList = ref([]);
const bpyPeopleIdList = ref([]);
const bpyPeopleNameList = ref([]);
const pyPeopleRef = ref(null);
const bpyPeopleRef = ref(null);
const peopleReviewRef = ref(null);
const orgReviewRef = ref(null);
const reviewResultRef = ref(null);
const sys_status = ref([{label: '执行中', value: '0'}, {label: '已结束', value: '1'}, {label: '未开始', value: '2'}]);

// 禁用大于结束日期
const disabledDateBegin = (time) => {
  if (form.value.end) {
    return time.getTime() > new Date(form.value.end).getTime();
  }
  return false;
};

// 禁用小于开始日期
const disabledDateEnd = (time) => {
  if (form.value.begin) {
    return time.getTime() < new Date(form.value.begin).getTime();
  }
  return false;
};

const data = reactive({
  form: {},
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    deptId: null,
    title: null,
    begin: null,
    end: null,
    details: null,
    files: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  },
  rules: {
    deptId: [
      { required: true, message: "发起组织不能为空", trigger: "blur" }
    ],
    title: [
      { required: true, message: "民主评议主题不能为空", trigger: "blur" }
    ],
    begin: [
      { required: true, message: "开始时间不能为空", trigger: "blur" }
    ],
    end: [
      { required: true, message: "结束时间不能为空", trigger: "blur" }
    ],
    bpyPeopleIdList: [
      { validator: (rule, value, callback) => {
          if (bpyPeopleNameList.value==null || bpyPeopleNameList.value=="") {
            callback(new Error("请选择民主评议对象")); 
          } else {
            callback(); 
          }
        }, 
        trigger: ["change", "blur"] 
      }
    ],
    pyPeopleIdList: [
      { validator: (rule, value, callback) => {
          if (pyPeopleNameList.value==null || pyPeopleNameList.value=="") {
            callback(new Error("请选择评议人员")); 
          } else {
            callback(); 
          }
        }, 
        trigger: ["change", "blur"] 
      }
    ]
  }
});

const { form, queryParams, rules } = toRefs(data);

function closePerson(index, type){
  if (type == 'bpy') {
    bpyPeopleIdList.value.splice(index, 1);
    bpyPeopleNameList.value.splice(index, 1);
  } else {
    pyPeopleIdList.value.splice(index, 1);
    pyPeopleNameList.value.splice(index, 1);
  }
}

//单击评议人员
function handleClickPyPeople() {
  pyPeopleRef.value.show();
}

//评议人员回调函数
function pyPeopleMethod(uIdList, uNameList) {
  if (uIdList!=null && uIdList.length>0) {
    uIdList.forEach((item, index) => {
      if (!pyPeopleIdList.value.includes(item)) {
        pyPeopleIdList.value.push(item);
        pyPeopleNameList.value.push(uNameList[index]);
      }
    });
  }
}

//单击民主评议对象
function handleClickBpyPeople() {
  bpyPeopleRef.value.show();
}

//民主评议对象回调函数
function bpyPeopleMethod(uIdList, uNameList) {
  if (uIdList!=null && uIdList.length>0) {
    uIdList.forEach((item, index) => {
      if (!bpyPeopleIdList.value.includes(item)) {
        bpyPeopleIdList.value.push(item);
        bpyPeopleNameList.value.push(uNameList[index]);
      }
    });
  }
}

// 重置评议人员和民主评议对象
function resetPyPeople() {
  pyPeopleIdList.value = [];
  pyPeopleNameList.value = [];
  bpyPeopleIdList.value = [];
  bpyPeopleNameList.value = [];
}

// 打开互评弹窗
function openPeopleReview(row) {
  peopleReviewRef.value.showPeopleEvalDlg(row.id);
}

// 打开支部评定弹窗
function openOrgReview(row) {
  orgReviewRef.value.showOrgEvalDlg(row.id);
}

// 打开评定结果弹窗
function openReviewResult(row) {
  reviewResultRef.value.showReviewResultDlg(row.id, row.title);
}

/** 查询评议列表 */
function getList() {
  loading.value = true;
  if (dateRange.value.length > 0) {
    if (dateRange.value[0] != null && dateRange.value[0] != null) {
      queryParams.value.begin = dateRange.value[0]+' 00:00:00';
    }
    if (dateRange.value[1] != null && dateRange.value[1] != null){
      queryParams.value.end = dateRange.value[1]+' 23:59:59';
    }
  }
  listReview(queryParams.value).then(response => {
    reviewList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    id: null,
    deptId: null,
    title: null,
    begin: null,
    end: null,
    details: null,
    files: null,
    createBy: null,
    createTime: null,
    updateBy: null,
    updateTime: null
  };
  proxy.resetForm("ReviewRef");
  resetPyPeople();
}

/** 查询部门下拉树结构 */
function getDeptTree() {
  listOrg().then(response => {
    deptOptions.value = proxy.handleTree(response.rows, "deptId");
  });
};

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  dateRange.value = [];
  queryParams.value.begin = null;
  queryParams.value.end = null;
  proxy.resetForm("queryRef");
  handleQuery();
}

// 多选框选中数据
function handleSelectionChange(selection) {
  ids.value = selection.map(item => item.id);
  single.value = selection.length != 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  isDisabled.value = false;
  title.value = "添加评议";
}

/** 查看按钮操作 */
function handleView(row) {
  reset();
  getReview(row.id).then(response => {
    form.value = response.data;
    let peopleArr = form.value.staffs;
    peopleArr.forEach(item => {
      if (item.type == 1) { //类型：0被评人1评定人
        pyPeopleIdList.value.push(item.userId);
        pyPeopleNameList.value.push(item.userName);
      } else {
        bpyPeopleIdList.value.push(item.userId);
        bpyPeopleNameList.value.push(item.userName);
      }
    });
    open.value = true;
    isDisabled.value = true;
    title.value = "查看评议";
  });
}

// 获取组织名称
function handleClickOrginize(data) {
  form.value.deptName = data.label;
}

/** 提交按钮 */
function submitForm() {
  proxy.$refs["ReviewRef"].validate(valid => {
    if (valid) {
      let staffs = [];
      if (pyPeopleIdList.value.length > 0) {
        for (let i = 0; i < pyPeopleIdList.value.length; i++) {
          let obj = {};
          obj.type = 1; // 类型：0被评人1评定人
          obj.userId = pyPeopleIdList.value[i];
          obj.userName = pyPeopleNameList.value[i];
          staffs.push(obj);
        }
      }
      if (bpyPeopleIdList.value.length > 0) {
        for (let i = 0; i < bpyPeopleIdList.value.length; i++) {
          let obj = {};
          obj.type = 0; // 类型：0被评人1评定人
          obj.userId = bpyPeopleIdList.value[i];
          obj.userName = bpyPeopleNameList.value[i];
          staffs.push(obj);
        }
      }
      form.value.staffs = staffs;
      addReview(form.value).then(response => {
        proxy.$modal.msgSuccess("新增成功");
        open.value = false;
        getList();
      });
    }
  });
}

/** 删除按钮操作 */
function handleDelete(row) {
  const _ids = row.id || ids.value;
  proxy.$modal.confirm('是否确认删除评议编号为"' + _ids + '"的数据项？').then(function() {
    return delReview(_ids);
  }).then(() => {
    getList();
    proxy.$modal.msgSuccess("删除成功");
  }).catch(() => {});
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download('partybuilding/Review/export', {
    ...queryParams.value
  }, `Review_${new Date().getTime()}.xlsx`)
}

getDeptTree();
getList();
</script>

<style lang="scss" scoped>
.el-dialog > .el-dialog__body {
  border-top: 1px solid red;
  border-bottom: 1px solid #e9e9e9;
}
.spanUserTitle {
  height: 22px;
  background-color: rgb(255, 255, 255);
  color: rgb(51, 51, 51);
  font-size: 16px;
  text-align: left;
  font-family: PingFangSC-Regular;
}
.itemTogetherTitle {
    font-size: 14px;
    text-align: left;
    font-family: PingFangSC-Regular;
    color: rgb(153, 153, 153) !important;
    padding: 19px 59px;
}
.dialog-top-line {
  width: 100%;
  height: 1px;
  background-color: #ccc;
  position: absolute;
  left: 0px;
  top: 49px;
}
.dialog-bottom-line {
  width: 100%;
  height: 1px;
  background-color: #ccc;
  position: absolute;
  left: 0px;
  bottom: 65px;
}
.formPeopleStyle {
  position: relative;
}
.formPeopleStyle::before {
  content: "*";
  color: #F56C6C;
  position: absolute;
  left: 4px;
  top: 9px;
}
.formPeopleStyle1 {
  position: relative;
}
.formPeopleStyle1::before {
  content: "*";
  color: #F56C6C;
  position: absolute;
  left: 30px;
  top: 9px;
}
.personDiv {
  margin: 5px;
}
.singlePersonDiv {
  position: relative;
  display: block;
  width: 64px;
  height: 66px;
  float: left;
  margin-top: 10px;
  margin-bottom: 15px;
  margin-right: 10px;
  cursor: pointer;
  .closeDiv {
      position: absolute;
      top: -11px;
      right: 7px;
      font-size: 16px;
      cursor: pointer;
   }
  .circleAndText {
      width: 44px;
      height: 44px;
      line-height: 44px;
      text-align: center;
      border-radius: 50%;
      border: 1px solid #ffe3e3;
      color: #333;
      font-size: 14px;
      background-color: rgba(255, 77, 79, .06);
  }
  .bottomText {
      font-size: 14px;
      color: #595959;
      margin-top: -1px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
  }
}
</style>